/**
 * 
 */
package cn.com.easy.weixin.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.github.sd4324530.fastweixin.company.api.response.GetOauthUserInfoResponse;

/**
 * 企业授权过滤器
 * 
 * @author nibili 2017年6月22日下午4:29:37
 * 
 */
//@Component
public class QywxAuthFilterDemo extends OncePerRequestFilter {

	/** 用于从 session中取是否已微信授权 */
	public static final String QYWX_AUTH_USER = "QYWX_AUTH_USER";
	/** 用于从session中取授权后要跳转的最终url */
	public static final String QYWX_AUTH_BACK_URL_KEY = "qywxBackUrl";

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		HttpSession httpSession = request.getSession();
		GetOauthUserInfoResponse getOauthUserInfoResponse = (GetOauthUserInfoResponse) httpSession.getAttribute(QYWX_AUTH_USER);
		if (getOauthUserInfoResponse == null) {
			// 已授权
			filterChain.doFilter(request, response);
			return;
		} else {
			// 未授权,保存最终要跳转的url到session中，然后请求授权链接
			String lastAccessUrl = request.getRequestURL().toString();
			String queryString = request.getQueryString();
			if (StringUtils.isNotBlank(queryString) == true) {
				lastAccessUrl = lastAccessUrl + "?" + queryString;
			}
			httpSession.setAttribute(QYWX_AUTH_BACK_URL_KEY, lastAccessUrl);
			// 请求授权链接
			response.sendRedirect("/kangwu/weixin/oauth");
		}

	}

}
